package databases;



import negocio.Lancamento;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;

public class DsLancamento {
	private SQLiteDatabase db;
	private Db banco;
	private String[] columns = {"_id", "id_conta", "id_favorecido", "id_categoria", "data", "valor", "pago", "tipo"};
	
	public DsLancamento(Context context)
	{
		banco = new Db(context);
	}
	
	public void open() throws SQLException
	{
		db = banco.getWritableDatabase();
	}
	
	public void close()
	{
		db.close();
	}

	public Lancamento addLancamento(Lancamento lanc)
	{
		ContentValues values = new ContentValues();
		values.put("id_conta", lanc.getIdConta());
		values.put("id_favorecido", lanc.getIdFavorecido());
		values.put("id_categoria", lanc.getIdCategoria());
		values.put("tipo", lanc.getTipo());
		values.put("valor", lanc.getValor());
		values.put("data", lanc.getData().getTime());
		
		long insertId = db.insert("Lancamento", null, values);
		Cursor cursor = db.query("Lancamento", columns, "_id = " + insertId, null, null, null, null);
		
		cursor.moveToFirst();
		Lancamento newLanc = cursorToLancamento(cursor);
		cursor.close();
		
		return newLanc;
	}
	
	public boolean hasLancamentoCategoria(long id){
		return hasLancamentoReference(id, "id_categoria");
	}
	
	public boolean hasLancamentoConta(long id){
		return hasLancamentoReference(id, "id_conta");
	}
	
	public boolean hasLancamentoFavorecido(long id){
		return hasLancamentoReference(id, "id_favorecido");
	}
	
	private Lancamento cursorToLancamento(Cursor cursor)
	{
		Lancamento lanc = new Lancamento();
		
		lanc.setId(cursor.getLong(0));
		lanc.setTipo(cursor.getInt(1));
		
		return lanc;
	}
	
	private boolean hasLancamentoReference(long id, String column)
	{
		Cursor cursor = db.query("Lancamento", columns, column + " = " + id, null, null, null, null);
		
		if (cursor.getCount()>0){
			cursor.close();
			return true;
		}else{
			cursor.close();
			return false;
		}
	}
}